package org.codeart.juc.util;

import java.util.concurrent.Semaphore;

/**
 * 信号量
 */
public class SemaphoreDemo {

    public static void main(String[] args) throws InterruptedException {
        Semaphore signal = new Semaphore(10);
        new Thread(() -> {
            System.out.println("要获取3个资源");
            try {
                signal.acquire(3);
                System.out.println("获取了3个资源");
                Thread.sleep(10000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                signal.release(3);
            }
        }).start();

        for (int i = 0; i < 7; i++) {
            int temp = i;
            new Thread(() -> {
                System.out.println("剩余的线程要进来: " + temp);
                try {
                    signal.acquire();
                    System.out.printf("线程 %s 进来了\n", temp);
                    Thread.sleep(10000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    signal.release();
                }
            }).start();
        }

        Thread.sleep(100);
        System.out.println("Main线程要进入");
        if (signal.tryAcquire()) {
            System.out.println("Main线程进来了");
            signal.release();
        } else {
            System.out.println("资源不够，Main线程进不来");
        }
    }

}
